package com.tangyh.basic.utils.oldProject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

@Component
@Slf4j
public class DataServiceNewUtil {

    private static String appcode;

    @Value("${business.app-code}")
    public void setAppcode(String appcode) {
        DataServiceNewUtil.appcode = appcode;
    }

    static final String CHASET_UTF_8 = "UTF-8";
    private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 图片识别接口
     * imgUrl
     * side (face：正面,back：背面)
     *
     * @return
     */
    public static JSONObject tpsbService(byte[] content, String side) {

        String host1 = "http://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);
        String config_str = configObj.toString();
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        // 对图像进行base64编码
        String imgBase64 = new String(encodeBase64(content));
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            if (response != null) {
                int stat = response.getStatusLine().getStatusCode();
                if (stat != 200) {
                    log.info("Http code: " + stat);
                    log.info(">>>身份证识别失败原因: {}" , response.getFirstHeader("X-Ca-Error-Message"));
                    log.info(">>>身份证识别失败原因2:{}" ,EntityUtils.toString(response.getEntity()));
                    return null;
                }

                String res = EntityUtils.toString(response.getEntity());
                JSONObject res_obj = JSON.parseObject(res);
                if (is_old_format) {
                    JSONArray outputArray = res_obj.getJSONArray("outputs");
                    String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                    JSONObject out = JSON.parseObject(output);
                    System.out.println(out.toJSONString());
                    return out;
                } else {
                    System.out.println(res_obj.toJSONString());
                    return res_obj;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图片识别接口
     * imgUrl
     * side (face：正面,back：背面)
     *
     * @return
     */
    public static JSONObject tpsbService(String imgUrl, String side) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "3bd295a088134907b9caa4c27d808e19";
        String imgFile = imgUrl;
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", side);
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //            String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = "";
        try {
            File file = new File(imgFile);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            if (response != null) {
                int stat = response.getStatusLine().getStatusCode();
                if (stat != 200) {
                    System.out.println("Http code: " + stat);
                    System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                    System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                    return null;
                }

                String res = EntityUtils.toString(response.getEntity());
                JSONObject res_obj = JSON.parseObject(res);
                if (is_old_format) {
                    JSONArray outputArray = res_obj.getJSONArray("outputs");
                    String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                    JSONObject out = JSON.parseObject(output);
                    System.out.println(out.toJSONString());
                    return out;
                } else {
                    System.out.println(res_obj.toJSONString());
                    return res_obj;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 身份证姓名核验接口
     *
     * @param idCard
     * @param name
     * @return
     */
    public static JSONObject idCarService(String idCard, String name) {
//        String host = "https://idcardcert.market.alicloudapi.com";
        String host = "https://idcert.market.alicloudapi.com";

//        String path = "/idCardCert";
        String path = "/idcard";
        String method = "GET";
//        String appcode = "200bb1a4a3c542da8db1301911b61631";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139xxx
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("idCard", idCard);
        querys.put("name", name);
        //JDK 1.8示例代码请在这里下载：  http://code.fegine.com/java/cmapi029522.zip

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 或者直接下载：
             * http://code.fegine.com/HttpUtils.zip
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             * 相关jar包（非pom）直接下载：
             * http://code.fegine.com/aliyun-jar.zip
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
//            System.out.println(EntityUtils.toString(response.getEntity()));
            /** 正确返回
             * {
             *  "status": "01",                         状态码:详见状态码说明 01 通过，02不通过
             *  "msg":"实名认证通过！",                 提示信息
             *  "idCard":"511126199511111111",          身份证号
             *  "name":"张三",                          姓名
             *  "sex":"男",                             性别
             *  "area":"四川省乐山市夹江县",            身份证所在地(参考)
             *  "province":"四川省",                    省(参考)
             *  "city":"乐山市",                        市(参考)
             *  "prefecture":"夹江县",                  区县(参考)
             *  "birthday":"1995-11-11",                出生年月
             *  "addrCode":"511126",                    地区代码
             *  "lastCode":"1"                          身份证校验码
             * }
             */
            /** 失败返回
             * {
             *    "status": "02",                          状态码:详见状态码说明 01 通过，02不通过
             *        "msg": "实名认证不通过！",                 提示信息
             *        "idCard": "510703198602170052",          身份证号
             *        "name": "伍帅",                          姓名
             *        "sex": "",                               实名认证不通过时以下都为空
             *        "area": "",
             *        "province": "",
             *        "city": "",
             *        "prefecture": "",
             *        "birthday": "",
             *        "addrCode": "",
             *        "lastCode": ""
             * }
             */
            /** 错误码定义
             * 01	实名认证通过！	实名认证通过！
             * 02	实名认证不通过！	实名认证不通过！
             * 202	无法验证！【中心中无此身份证记录，军人转业，户口迁移等】	无法验证！【中心中无此身份证记录，军人转业，户口迁移等】
             * 203	异常情况！	异常情况！
             * 204	姓名格式不正确！	姓名格式不正确！
             * 205	身份证格式不正确！	身份证格式不正确！
             */
            JSONObject res_obj = JSON.parseObject(EntityUtils.toString(response.getEntity()));
            System.out.println(res_obj.toString());
            return res_obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 银行卡接口检验
     *
     * @return
     */
    public static String backService(String acct_name, String acct_pan, String cert_id, String phone_num) {
        String host = "http://lundroid.market.alicloudapi.com";
        String path = "/lianzhuo/verifi";
        String method = "GET";
//        String appcode = "200bb1a4a3c542da8db1301911b61631";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("acct_name", acct_name);
        querys.put("acct_pan", acct_pan);
        querys.put("cert_id", cert_id);
        querys.put("phone_num", phone_num);

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            String res = EntityUtils.toString(response.getEntity(), "utf-8");
//            JSONObject res_obj = JSON.parseObject(res);
            System.out.println(res);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String postForm(Map<String, String> params) throws IOException {
        String url = "https://mobile3elements.shumaidata.com/mobile/verify_real_name";
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appcode).post(body).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }

    /*
     * 获取参数的json对象
     */
    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void main(String[] args) {
        tpsbService("C:\\Users\\wujix\\Pictures\\微信图片_20211105155336.jpg","face");
//        tpsbService("C:\\Users\\user\\Desktop\\图片素材\\微信图片_20180308140838.jpg","back");
//        idCarService("430725200009053961", "连敏");
//        idCarService("32092319991114091X","周航");
//        idCarService("320124198902083237","刘昊");
//        try {
//            Map<String,String> params = new HashMap<>();
//            params.put("idcard","320124198902083237");
//            params.put("mobile","13140701903");
//            params.put("name","刘昊");
//            String res = DataServiceNewUtil.postForm(params);
//            System.out.println("三要素认证返回结果："+res);
//        } catch (Exception e) {
//            e.getStackTrace();
//        }
//        backService("连敏","6217002920141122284","430725200009053961","17397366902");
//        backService("连敏","6217002920141122284","430725200009053961","");
//        backService("姜勤","6214868710456996","650103197106190023","18187011815");
//        backService("姜勤","6214868710456996","650103197106190023","");
//        backService("涂昀睿","6214838776627376","530102199002011188","13759490811");
//        backService("涂昀睿","6214838776627376","530102199002011188","");
    }
}
